const app = getApp();
const pageSize = 20;

Page({

  data: {
    list: [],
    template_species: 2,
    nomore: false,
    loadmore: false,
    empty: false,
    isFranchiser: false, //是否是加盟商
    franchisers: [],
  },




  onLoad: function (options) {
    let isFranchiser = options.is_franchiser || false; //是否是加盟商
    //type模版种类，1：充值（充M送N），2：设备（售水参数），3：合伙人充值模版（充M送N)
    const type = options.type || 2;
    const titles = ["用户自助充值模板", "价格模板", "代客充值模板"];
    let title = titles[type - 1];
    wx.setNavigationBarTitle({
      title,
    })
    this.setData({
      template_species: type,
      isFranchiser
    })
    this.page = 1;
    if (this.data.isFranchiser) {
      this.getFranchisers();
    } else {
      this.getTemplateList();
    }
  },


  //获取合伙人的加盟商
  getFranchisers() {
    app.ajax({
      url: "Partner/Franchiser/franchiserList",
      success: res => {
        if (res.data.code == 5000) {
          let source = res.data.data;
          this.setData({
            franchisers: source,
          })
          this.getTemplateList();
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },


  //设置默认模板
  handleSetDefault(e) {
    const index = e.currentTarget.dataset.index;
    const template = this.data.list[index];
    if (template.template_status == 2) {
      app.showToast("请先启用模板");
      return false;
    }
    if (template.is_default == 1) return;
    wx.showModal({
      content: `是否设置[${template.template_title}]设为默认模板？`,
      success: results => {
        if (results.confirm) {
          app.ajax({
            url: "Partner/Village/templateDefault",
            data: {
              id: template.id,
              is_default: 1
            },
            success: res => {
              if (res.data.code == 1000) {
                app.showToast(res.data.message, "success");
                setTimeout(() => {
                  this.reloadData()
                }, 1500)
              } else {
                app.showToast(res.data.message);
              }
            }
          })
        }
      },
      fail: error => {
        console.log(error)
      }
    })
  },


  //启用&禁用模板
  changeSwitch(e) {
    const index = e.currentTarget.dataset.index;
    const temp_status = this.data.list[index].template_status;
    app.ajax({
      url: "Partner/Village/templateStatus",
      data: {
        id: this.data.list[index].id,
        template_status: temp_status == 1 ? 2 : 1
      },
      success: res => {
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          this.setData({
            [`list[${index}].template_status`]: temp_status == 1 ? 2 : 1
          })
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        app.showToast("网络错误")
      }
    })
  },

  //删除模板
  deleteTemplate(e) {
    const index = e.currentTarget.dataset.index;
    let template = this.data.list[index];
    wx.showModal({
      content: `是否删除模板[${template.template_title}]？`,
      success: result => {
        if (result.confirm) {
          app.ajax({
            url: "Partner/Village/editTemplate",
            data: {
              id: template.id,
              is_delete: true
            },
            success: res => {
              if (res.data.code == 1000) {
                app.showToast(res.data.message, "success");
                setTimeout(() => {
                  this.reloadData()
                }, 1500)
              } else {
                app.showToast(res.data.message)
              }
            },
            error: e => {
              app.showToast("网络错误")
            }
          })
        }
      },
      fail: error => {
        console.log(error)
      }
    })
  },

  //钩子触底事件
  onReachBottom: function () {
    if (this.data.loadmore) {
      ++this.page;
      this.getTemplateList();
    }
  },

  onPullDownRefresh: function () {
    this.reloadData();
  },

  //重载数据
  reloadData() {
    this.page = 1;
    this.setData({
      list: [],
      nomore: false,
      loadmore: false
    })
    this.getTemplateList();
  },

  //获取列表
  getTemplateList() {
    let param = {
      page: this.page,
      row: pageSize,
      template_species: this.data.template_species
    }
    if (this.data.isFranchiser) {
      param.type = 1;
    }
    app.ajax({
      url: "Partner/Village/templateList",
      data: param,
      success: res => {
        wx.hideLoading();
        wx.stopPullDownRefresh()
        if (res.data.code == 1000) {
          const source = res.data.data.data;
          const total = res.data.data.page.total_number + 1;
          source.forEach(item => {
            if (this.data.template_species != 2) {
              item.template = Object.values(item.template)
            }
            if (this.data.isFranchiser) {
              let index = this.data.franchisers.findIndex(current => current.id == item.partner_id);
              item.partner_name = ~index ? this.data.franchisers[index].account_name : '';
            }
          })
          let list = this.data.list.concat(source);
          this.setData({
            empty: total == 0 ? true : false,
            list,
            nomore: total >= list.length ? true : false,
            loadmore: total < list.length ? true : false,
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        wx.hideLoading()
        wx.stopPullDownRefresh()
        app.showToast("网络错误");
      }
    })
  },

  add() {
    wx.navigateTo({
      url: `add?type=${this.data.template_species}&mode=1${this.data.isFranchiser?'&is_franchiser=1':''}`,
    })
  },

  editTemplate(e) {
    const index = e.currentTarget.dataset.index;
    let template = this.data.list[index];
    wx.navigateTo({
      url: `add?type=${this.data.template_species}&id=${template.id}${this.data.isFranchiser?'&is_franchiser=1':''}`,
      success: res => {
        res.eventChannel.emit("openTemplateAdd", {
          ...template
        });
      }
    })
  },


})